package cn.lr.basic.interceptor;

import cn.lr.basic.annotation.PreAuthorize;
import cn.lr.basic.jwt.JwtUtils;
import cn.lr.basic.jwt.Payload;
import cn.lr.basic.jwt.RsaUtils;
import cn.lr.basic.jwt.UserInfo;
import cn.lr.system.mapper.PermissionMapper;
import cn.lr.user.domain.Logininfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.FileCopyUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.security.PublicKey;
import java.util.List;

/**
 *  自定义登录拦截器
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private PermissionMapper permissionMapper;
    @Value("${jwt.rsa.pub}")
    private String jwtRsaPublic;
    @Override
    public boolean preHandle(HttpServletRequest req, HttpServletResponse resp, Object handler) throws Exception {
        // 从请求头中获取token
        String token = req.getHeader("U-TOKEN");
        resp.setCharacterEncoding("UTF-8"); // 设置字符集
        resp.setContentType("application/json;charset=utf-8");
        // 判断token是否存在
        if(!StringUtils.isEmpty(token)){
            //2.根据token 解密token得到登录人相关的所有信息
            PublicKey publicKey = RsaUtils
                    .getPublicKey((FileCopyUtils
                            .copyToByteArray(this.getClass().getClassLoader().getResourceAsStream(jwtRsaPublic))));
            Payload<UserInfo> payload = JwtUtils.getInfoFromToken(token, publicKey, UserInfo.class);
            UserInfo userInfo = payload.getUserInfo();
            Logininfo loginTemp = userInfo.getUser();
            if(loginTemp != null){
                // 员工登录要拦截所有权限请求
                if(loginTemp.getType() == 0){ // 根据type判断是员工还是用户
                    // 是员工，校验当前员工是否有访问资源的权限
                    HandlerMethod method = (HandlerMethod)handler;
                    PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
                    if(preAuthorize != null){ // 当前方法上有这个注解，就需要校验，拥有权限后才能访问
                        String sn = preAuthorize.value(); // 获取请求的资源
                        // 查出当前登录人拥有的权限资源
                        List<String> ownPermissions = userInfo.getPermissions();
                        if(!ownPermissions.contains(sn)){
                            PrintWriter writer = resp.getWriter();
                            writer.print("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                    }
                }
                // 用户登录直接放行
                // 刷新过期时间
                return true; // 放行
            }
        }
        PrintWriter writer = resp.getWriter();
        writer.write(" {\"success\":false,\"message\":\"noLogin\"}"); // 向前端返回json格式对象
        writer.flush(); // 刷新
        writer.close(); // 关流
        return false; // 阻止放行
    }
       /* @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.判断有没有携带token
        String token = request.getHeader("U-TOKEN");//JWT串
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json; charset=UTF-8");
        if(!StringUtils.isEmpty(token)){
            //2.根据token从redis获取登陆人信息
            Object loginTmp = redisTemplate.opsForValue().get(token);
            if(loginTmp != null){
                // 看是否是员工还是用户
                Logininfo logininfo = (Logininfo) loginTmp;
                if(logininfo.getType() == 0){
                    //如果是员工
                    //1.需要单独校验当前登录的员工，是否有权限访问当前资源
                    HandlerMethod method = (HandlerMethod) handler;
                    PreAuthorize preAuthorize = method.getMethodAnnotation(PreAuthorize.class);
                    if(preAuthorize != null){//当前这个方法打了注解，那么就需要校验权限，拥有权限，才能访问
                        //。获取当前请求的资源
                        String permisionSn = preAuthorize.value();
                        //。查询出当前登录人所拥有的资源权限
                        List<String> ownPers = permissionMapper.loadOwnPermissionByLoginInfoId(logininfo.getId());
                        //。比对当前访问的资源是否包含在登录人所拥有的权限中
                        if(!ownPers.contains(permisionSn)){
                            //--如果不在 提示没有权限访问，直接返回 {"success":false,"message":"noPermission"}
                            PrintWriter writer = response.getWriter();
                            writer.write("{\"success\":false,\"message\":\"noPermission\"}");
                            writer.flush();
                            writer.close();
                            return false;//阻止放行
                        }
                        //--如果在  放行
                    }
                }
                //如果是用户，直接放行，不用校验权限
                //3.有，放行 刷新过期时间
                redisTemplate.opsForValue().set(token,loginTmp,30, TimeUnit.MINUTES);
                return true;//放行
            }
        }
        // 报错 让前端定位到登录页 向response中写AJaxResult
        PrintWriter writer = response.getWriter();
        writer.write("{\"success\":false,\"message\":\"noLogin\"}");
        writer.flush();
        writer.close();
        return false;//阻止放行
    }*/

}
